package main.com.controller;

import main.com.dao.UserDao;
import main.com.entry.User;
import main.com.utils.CheckUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author lk
 * @date 2020/6/23 11:28
 * @description: 用户信息处理
 */
@WebServlet("/user")
public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = (String) request.getSession().getAttribute("username");
        if (username == null) {//未登录
            response.sendRedirect("login.jsp");
        } else {
            UserDao userDao = new UserDao();
            User user = userDao.selectAll(username);
            if (user==null){//该用户不存在（依旧未登录）
                response.sendRedirect("login.jsp");
            }
            request.setAttribute("user",user);
            request.getRequestDispatcher("userdetails.jsp").forward(request, response);
        }

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = (String) request.getSession().getAttribute("username");
        String flag = request.getParameter("flag");
        UserDao userDao = new UserDao();
        if (username == null) {//未登录
            response.sendRedirect("login.jsp");
        } else if ("e".equals(flag)) {//修改邮箱
            String email = request.getParameter("email");
            String msg = CheckUtil.checkEmail(email);
            if ("ok".equals(msg)){
                userDao.updateEmail(email,username);
            }
            request.setAttribute("msg", msg);
            request.getRequestDispatcher("wel-edit.jsp").forward(request, response);
        } else if ("p".equals(flag)) {//修改密码
            String password = request.getParameter("password");
            if (userDao.checkUser(username).equals(password)) {
                String newpassword = request.getParameter("newpassword");
                String newpassword1 = request.getParameter("newpassword1");
                String msg = CheckUtil.checkPassWord(newpassword,newpassword1);
                if ("ok".equals(msg)){
                    userDao.updatePassword(newpassword,username);
                }
                request.setAttribute("msg", msg);
            }else {
                request.setAttribute("msg", "原密码输入错误");
            }
            request.getRequestDispatcher("wel-edit.jsp").forward(request, response);
        }
    }
}
